package com.zatech.cgnci.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.enums.ApprovalConfigEnum;
import com.zatech.cgnci.project.base.enums.BusinessScenariosEnum;
import com.zatech.cgnci.project.base.enums.OperationTypeEnum;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.AreaUtils;
import com.zatech.cgnci.project.base.utils.ConvertUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.dto.*;
import com.zatech.cgnci.project.entity.*;
import com.zatech.cgnci.project.mapper.CgnciApprovalConfigMapper;
import com.zatech.cgnci.project.mapper.CgnciApprovalInfoMapper;
import com.zatech.cgnci.project.mapper.CgnciApprovalRecordMapper;
import com.zatech.cgnci.project.mapper.CgnciReInsuranceCompanyMapper;
import com.zatech.cgnci.project.service.*;
import com.zatech.cgnci.project.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 再保公司表 服务实现类
 * </p>
 *
 * @author Generator
 * @since 2024-12-17
 */
@Slf4j
@Service
public class CgnciReInsuranceCompanyServiceImpl extends ServiceImpl<CgnciReInsuranceCompanyMapper, CgnciReInsuranceCompanyDO> implements CgnciReInsuranceCompanyService {

    @Resource
    CgnciReInsuranceCompanyAccountService reInsuranceCompanyAccountService;
    @Resource
    CgnciAccessoryService accessoryService;
    @Resource
    IApprovalService approvalService;
    @Resource
    CgnciApprovalInfoMapper approvalInfoMapper;
    @Resource
    CgnciApprovalConfigMapper approvalConfigMapper;
    @Resource
    private CgnciMessageSendService messageSendService;
    @Resource
    CgnciApprovalConfigRoleUserService approvalConfigRoleUserService;
    @Resource
    CgnciApprovalRecordMapper approvalRecordMapper;
    @Resource
    private CgnciCodeTypeService cgnciCodeTypeService;
    @Resource
    private CgnciOperationLogsService cgnciOperationLogsService;
    @Resource
    private CgnciApprovalRecordService approvalRecordService;
    @Resource
    private CgnciReinsurerRatingService reinsurerRatingService;

    @Override
    public IPage<CgnciReInsuranceCompanyPageVO> pageInsuranceCompany(CgnciReInsuranceCompanyQueryDTO dto) {
        return this.baseMapper.pageInsuranceCompany(dto.toPage(), dto);
    }

    @Override
    public CgnciReInsuranceCompanyMainVO detail(Long id) {
        CgnciReInsuranceCompanyMainVO reInsuranceCompanyMainVO = new CgnciReInsuranceCompanyMainVO();
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = this.baseMapper.selectById(id);
        reInsuranceCompanyMainVO.setReInsuranceCompanyVO(ConvertUtils.convert(reInsuranceCompanyDO, CgnciReInsuranceCompanyVO.class));

        // 任务流程和镜像数据1对1
        CgnciApprovalInfoDO approvalInfoDO = approvalInfoMapper.selectOne(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                .eq(CgnciApprovalInfoDO::getFormId, reInsuranceCompanyDO.getId())
                .eq(CgnciApprovalInfoDO::getFormNo, reInsuranceCompanyDO.getFormNo()));
        if (VerifyUtils.isNotEmpty(approvalInfoDO)) {
            reInsuranceCompanyMainVO.setApprovalInfoId(approvalInfoDO.getApprovalInfoId());
            reInsuranceCompanyMainVO.setTaskId(approvalInfoDO.getTaskId());
            reInsuranceCompanyMainVO.setTaskType(approvalInfoDO.getTaskType());
        }

        List<CgnciReInsuranceCompanyAccountDO> accountList = reInsuranceCompanyAccountService.list(new LambdaQueryWrapper<CgnciReInsuranceCompanyAccountDO>().eq(CgnciReInsuranceCompanyAccountDO::getCompanyId, id));
        reInsuranceCompanyMainVO.setAccountList(ConvertUtils.convert(accountList, CgnciReInsuranceCompanyAccountVO.class));

        List<CgnciAccessoryDO> accessoryList = accessoryService.list(new LambdaQueryWrapper<CgnciAccessoryDO>().eq(CgnciAccessoryDO::getBusinessId, id));
        reInsuranceCompanyMainVO.setAccessoryList(ConvertUtils.convert(accessoryList, CgnciAccessoryVO.class));
        return reInsuranceCompanyMainVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CgnciReInsuranceCompanyDO saveOrUpdateInsuranceCompany(CgnciReInsuranceCompanySaveOrUpdateDTO updateDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();

        // 校验再保公司id
        CgnciReInsuranceCompanyDO checkCompany = this.getById(updateDTO.getReInsuranceCompanyDTO().getId());
        if (VerifyUtils.isEmpty(checkCompany)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "id有误");
        }

        // 校验状态
        if (!"0".equals(checkCompany.getStatus()) && !"2".equals(checkCompany.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "当前状态不能录入");
        }
        if (VerifyUtils.isNotEmpty(updateDTO.getFlowTaskType()) && "submit".equals(updateDTO.getFlowTaskType())) {
            // 提交审核校验数据
            // 再保公司中文名称重复，请修改
            CgnciReInsuranceCompanyDO checkCompanyNameCn = this.getOne(new LambdaQueryWrapper<CgnciReInsuranceCompanyDO>()
                    .eq(CgnciReInsuranceCompanyDO::getCompanyNameCn, updateDTO.getReInsuranceCompanyDTO().getCompanyNameCn())
                    .eq(CgnciReInsuranceCompanyDO::getIsMirror, "0")
                    .notIn(CgnciReInsuranceCompanyDO::getFormNo,checkCompany.getFormNo())
                    .notIn(CgnciReInsuranceCompanyDO::getStatus, Arrays.asList("0", "2", "4")));
            if (VerifyUtils.isNotEmpty(checkCompanyNameCn)) {
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "再保公司中文名称重复，请修改");
            }

            // 评级为空时，再保人评级审核文件必传
            /*if (VerifyUtils.isEmpty(updateDTO.getReInsuranceCompanyDTO().getRating())) {
                List<CgnciReInsuranceCompanySaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = updateDTO.getAccessoryDTOList();
                if (VerifyUtils.isEmpty(accessoryDTOList)) {
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传再保人评级审核文件");
                }
                List<Long> accIds = accessoryDTOList.stream().map(CgnciReInsuranceCompanySaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
                List<CgnciAccessoryDO> accessoryList = accessoryService.listByIds(accIds);
                CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "reinsurerRatingReviewDoc".equals(acc.getAccType())).findFirst().orElse(null);
                if (VerifyUtils.isEmpty(accessory)) {
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传再保人评级审核文件");
                }
            }*/
        }

        // 维护业务名称到工作台
        CgnciApprovalInfoDO approvalInfoDO = approvalInfoMapper.selectOne(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                .eq(CgnciApprovalInfoDO::getFormId, updateDTO.getReInsuranceCompanyDTO().getId()));
        if (VerifyUtils.isEmpty(approvalInfoDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "任务流程不存在");
        }
        approvalInfoDO.setBusinessName(updateDTO.getReInsuranceCompanyDTO().getCompanyNameCn());
        approvalInfoMapper.updateById(approvalInfoDO);


        CgnciReInsuranceCompanySaveOrUpdateDTO.CgnciReInsuranceCompanyDTO reInsuranceCompanyDTO = updateDTO.getReInsuranceCompanyDTO();
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = ConvertUtils.convert(reInsuranceCompanyDTO, CgnciReInsuranceCompanyDO.class);
        reInsuranceCompanyDO.setCreateUser(VerifyUtils.isEmpty(reInsuranceCompanyDO.getCreateUser()) ? user.getNameAndCode() : reInsuranceCompanyDO.getCreateUser());
        reInsuranceCompanyDO.setUpdateUser(user.getNameAndCode());
        this.saveOrUpdate(reInsuranceCompanyDO);

        List<CgnciReInsuranceCompanySaveOrUpdateDTO.ReInsuranceCompanyAccountDTO> accountDTOList = updateDTO.getAccountDTOList();
        if (VerifyUtils.isNotEmpty(accountDTOList)) {
            List<CgnciReInsuranceCompanyAccountDO> reInsuranceCompanyAccountList = ConvertUtils.convert(accountDTOList, CgnciReInsuranceCompanyAccountDO.class);
            reInsuranceCompanyAccountList.forEach(account -> {
                account.setCompanyId(reInsuranceCompanyDO.getId());
                account.setBankProvince(AreaUtils.getNameById(account.getBankProvinceCode()));
                account.setBankCity(AreaUtils.getNameById(account.getBankCityCode()));
                account.setBankDistrict(AreaUtils.getNameById(account.getBankDistrictCode()));
                account.setCreateUser(user.getNameAndCode());
                account.setUpdateUser(user.getNameAndCode());
            });
            reInsuranceCompanyAccountService.saveOrUpdateBatch(reInsuranceCompanyAccountList);
        }

        List<CgnciReInsuranceCompanySaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = updateDTO.getAccessoryDTOList();
        if (VerifyUtils.isNotEmpty(accessoryDTOList)) {
            List<CgnciAccessoryDO> accessoryDOList = ConvertUtils.convert(accessoryDTOList, CgnciAccessoryDO.class);
            accessoryDOList.forEach(accessory -> {
                // 文件绑定业务数据
                accessory.setBusinessId(reInsuranceCompanyDO.getId());
            });
            accessoryService.saveOrUpdateBatch(accessoryDOList);
        }
        return reInsuranceCompanyDO;
    }

    @Override
    public CgnciReInsuranceCompanyDO nextEdit(Long id) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验再保公司id
        CgnciReInsuranceCompanyDO checkCompany = this.getById(id);
        if (VerifyUtils.isEmpty(checkCompany)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "id有误");
        }

        // 只有已完成才能编辑
        if (!"3".equals(checkCompany.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "当前状态不能编辑");
        }

        // 校验该年度承保计划是否已编辑
        // 校验同一个分组,同一个业务编号是否结束,否则抛出异常
        CgnciApprovalInfoDO approvalInfoDO = approvalInfoMapper.selectOne(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                .eq(CgnciApprovalInfoDO::getFormNo, checkCompany.getFormNo())
                .eq(CgnciApprovalInfoDO::getApprovalConfigGroupId, "004")
                .eq(CgnciApprovalInfoDO::getStatus, "3"));
        if (VerifyUtils.isNotEmpty(approvalInfoDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该险种最大净自留限额已经被编辑,不能再次编辑");
        }


        CgnciReInsuranceCompanyMainVO detailVO = this.detail(id);
        CgnciReInsuranceCompanyVO reInsuranceCompanyVO = detailVO.getReInsuranceCompanyVO();
        // 保存业务主表数据
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = ConvertUtils.convert(reInsuranceCompanyVO, CgnciReInsuranceCompanyDO.class);
        // 设置插入数据
        reInsuranceCompanyDO.setId(null);
        // 使用之前的流程编号绑定业务数据,目的是用来关联工作流,校验同一流程只能有一个在途的任务
        reInsuranceCompanyDO.setFormNo(checkCompany.getFormNo());
        // 设置该数据为镜像数据
        reInsuranceCompanyDO.setIsMirror("1");
        reInsuranceCompanyDO.setStatus("0");
        reInsuranceCompanyDO.setIsEffective("0");
        reInsuranceCompanyDO.setCreateUser(user.getNameAndCode());
        reInsuranceCompanyDO.setCreateTime(new Date());
        reInsuranceCompanyDO.setUpdateUser(user.getNameAndCode());
        reInsuranceCompanyDO.setUpdateTime(new Date());
        this.save(reInsuranceCompanyDO);


        // 账户信息
        List<CgnciReInsuranceCompanyAccountVO> accountList = detailVO.getAccountList();
        List<CgnciReInsuranceCompanyAccountDO> reInsuranceCompanyAccountList = ConvertUtils.convert(accountList, CgnciReInsuranceCompanyAccountDO.class);
        if (VerifyUtils.isNotEmpty(reInsuranceCompanyAccountList)) {
            reInsuranceCompanyAccountList.forEach(account -> {
                // 设置插入数据,关联镜像数据
                account.setId(null);
                account.setCompanyId(reInsuranceCompanyDO.getId());
                account.setIsEffective("0");
                account.setCreateUser(user.getNameAndCode());
                account.setCreateTime(new Date());
                account.setCreateUser(user.getNameAndCode());
                account.setUpdateTime(new Date());
            });
            reInsuranceCompanyAccountService.saveBatch(reInsuranceCompanyAccountList);
        }

        // 文件信息
        List<CgnciAccessoryVO> accessoryVOList = detailVO.getAccessoryList();
        if (VerifyUtils.isNotEmpty(accessoryVOList)) {
            List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
            accessoryVOList.forEach(accessory -> {
                CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                // 设置插入数据
                accessoryDO.setAccId(null);
                accessoryDO.setBusinessId(reInsuranceCompanyDO.getId());
                accessoryDO.setCreateUser(user.getNameAndCode());
                accessoryDO.setCreateTime(new Date());
                accessoryDO.setUpdateUser(user.getNameAndCode());
                accessoryDO.setUpdateTime(new Date());
                accessoryList.add(accessoryDO);
            });
            accessoryService.saveBatch(accessoryList);
        }
        return reInsuranceCompanyDO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(FlowTaskSubmitDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = this.getById(flowTaskDTO.getFormId());
        // 校验再保公司是否存在
        if (VerifyUtils.isEmpty(reInsuranceCompanyDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        FlowTaskVO submit = approvalService.submit(flowTaskDTO);
        // 回调提交审核状态流程
        reInsuranceCompanyDO.setStatus(submit.getStatus());
        this.updateById(reInsuranceCompanyDO);
        //操作日志
        ApprovalRecordVO approvalRecordVo = approvalRecordService.getPreviousApprovalRecord(reInsuranceCompanyDO.getId());
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(reInsuranceCompanyDO.getId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.REINSURANCECOMPANY.getCode());
        if(approvalRecordVo.getGroupID().equals(ApprovalConfigEnum.APPROVAL_CONFIG_004.getGroupId())){
            operationLogsDTO.setOperationType(OperationTypeEnum.SUBMIT_EDIT_REINSURANCE_COMPANY_AUDIT.getCode());
        }else {
            operationLogsDTO.setOperationType(OperationTypeEnum.SUBMIT_REINSURANCE_COMPANY_AUDIT.getCode());
        }
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
        /*String content = String.format("{%s}{%s}{%s} 流转至{%s}", BusinessStatusEnum.getDescByCode(submit.getStatus()), approvalRecordVo.getTaskType(), approvalRecordVo.getTaskId(), approvalRecordVo.getCurrentApproverAndName());
        operationLogsDTO.setContent(content);
        operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
        operationLogsDTO.setCreator("系统");
        cgnciOperationLogsService.saveLog(operationLogsDTO);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(FlowTaskApprovalDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验再保公司是否存在
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = this.getById(flowTaskDTO.getFormId());
        if (VerifyUtils.isEmpty(reInsuranceCompanyDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }

        FlowTaskVO approve = approvalService.approve(flowTaskDTO);
        // 回调审批通过状态流程
        reInsuranceCompanyDO.setStatus(approve.getStatus());

        if (1 == approve.getIsEnd()) {
            reInsuranceCompanyDO.setIsMirror("0");
            reInsuranceCompanyDO.setIsEffective("1");

            // 查询再保公司账户信息
            List<CgnciReInsuranceCompanyAccountDO> list = reInsuranceCompanyAccountService.list(new LambdaQueryWrapper<CgnciReInsuranceCompanyAccountDO>()
                    .eq(CgnciReInsuranceCompanyAccountDO::getCompanyId, reInsuranceCompanyDO.getId()));
            list.forEach(account -> account.setIsEffective("1"));
            reInsuranceCompanyAccountService.updateBatchById(list);

            // 审批通过之后,根据工作流配置的模块id(模块id可以有多个分组任务,比如新增任务和编辑任务)查询所有的业务数据,
            // 需要把最新审批通过的业务数据变为不是镜像数据,之前不是镜像数据的业务数据变更为镜像数据
            List<CgnciApprovalInfoDO> cgnciApprovalInfoDOS = approvalInfoMapper.selectList(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                    .eq(CgnciApprovalInfoDO::getStatus, "3")
                    .eq(CgnciApprovalInfoDO::getFormNo, approve.getFormNo())
                    .orderByDesc(CgnciApprovalInfoDO::getCreateTime)
                    .last("limit 2"));
            //
            CgnciReInsuranceCompanyDO secondReInsuranceCompany = null;

            if (cgnciApprovalInfoDOS.size() == 2) {
                CgnciApprovalInfoDO firstApprovalInfo = cgnciApprovalInfoDOS.get(0);
                CgnciApprovalInfoDO secondApprovalInfo = cgnciApprovalInfoDOS.get(1);
                // 标记最近一条审批通过的业务数据为非镜像数据
                CgnciReInsuranceCompanyDO firstReInsuranceCompany = this.getById(firstApprovalInfo.getFormId());
                firstReInsuranceCompany.setIsMirror("0");
                firstReInsuranceCompany.setIsEffective("1");
                this.updateById(firstReInsuranceCompany);

                // 标记之后的一个业务数据为镜像数据
                secondReInsuranceCompany = this.getById(secondApprovalInfo.getFormId());
                secondReInsuranceCompany.setIsMirror("1");
                secondReInsuranceCompany.setIsEffective("0");
                this.updateById(secondReInsuranceCompany);
            }

            // 再保人评级调整到A-以下，显示调整的操作记录。根据信用评级列，BBB+、BBB、BBB-、其他都属于A-以下。
            // 查询不包含当前数据，同一formNo，审批状态已完成的再保公司.目的是为了获取到更新前到评级
            /*CgnciReInsuranceCompanyDO company = this.getOne(new LambdaQueryWrapper<CgnciReInsuranceCompanyDO>()
                    .eq(CgnciReInsuranceCompanyDO::getStatus, "3")
                    .eq(CgnciReInsuranceCompanyDO::getIsMirror, "0")
                    .eq(CgnciReInsuranceCompanyDO::getFormNo, reInsuranceCompanyDO.getFormNo())
                    .notIn(CgnciReInsuranceCompanyDO::getId, reInsuranceCompanyDO.getId()));*/
            if (Integer.parseInt(reInsuranceCompanyDO.getRatingCode()) > 7) {
                // 新增一条数据
                CgnciReinsurerRatingDO ratingDO = CgnciReinsurerRatingDO.builder()
                        .companyType(reInsuranceCompanyDO.getCompanyType()).companyCode(reInsuranceCompanyDO.getCompanyCode())
                        .companyChinese(reInsuranceCompanyDO.getCompanyNameCn()).companyEnglish(reInsuranceCompanyDO.getCompanyNameEn())
                        .ratingPost(reInsuranceCompanyDO.getRating())
                        .createUserName(reInsuranceCompanyDO.getCreateUser()).updateUserName(user.getNameAndCode()).build();
                if (VerifyUtils.isNotEmpty(secondReInsuranceCompany)) {
                    ratingDO.setRatingPre(secondReInsuranceCompany.getRating());
                }
                reinsurerRatingService.save(ratingDO);
            }

            // 再保公司评级下调时，需要提醒合规人员
            if (VerifyUtils.isNotEmpty(secondReInsuranceCompany)) {
                if (Integer.parseInt(reInsuranceCompanyDO.getRatingCode()) > Integer.parseInt(secondReInsuranceCompany.getRatingCode())) {
                    // 查询合规人员
                    List<CgnciApprovalConfigRoleUserDO> roleUserDOS = approvalConfigRoleUserService.list(new LambdaQueryWrapper<CgnciApprovalConfigRoleUserDO>()
                            .eq(CgnciApprovalConfigRoleUserDO::getTaskTypeCode, "004")
                            .eq(CgnciApprovalConfigRoleUserDO::getCurrentApproverNode, "合规审核"));
                    roleUserDOS.forEach(roleUser -> messageSendService.sendRatingDowngradeMessage(reInsuranceCompanyDO.getCompanyNameCn(), reInsuranceCompanyDO.getRating(), roleUser.getCurrentApprover()));
                }
            }


        }
        this.updateById(reInsuranceCompanyDO);


        //审批通过后记录日志
        ApprovalRecordVO approvalRecord = approvalRecordService.getPreviousApprovalRecord(reInsuranceCompanyDO.getId());
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(reInsuranceCompanyDO.getId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.REINSURANCECOMPANY.getCode());
        if(approvalRecord.getGroupID().equals(ApprovalConfigEnum.APPROVAL_CONFIG_004.getGroupId())){
            operationLogsDTO.setOperationType(OperationTypeEnum.EDIT_REINSURANCE_COMPANY_AUDIT_PASS.getCode());
        }else {
            operationLogsDTO.setOperationType(OperationTypeEnum.REINSURANCE_COMPANY_AUDIT_PASS.getCode());
        }
        operationLogsDTO.setContent(flowTaskDTO.getApproverOpinions());
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
        /*if (1 != approve.getIsEnd()) {
            String content = String.format("{%s}{%s}{%s} 流转至{%s}", BusinessStatusEnum.getDescByCode(approve.getStatus()), approvalRecord.getTaskType(), approvalRecord.getTaskId(), approvalRecord.getCurrentApproverAndName());
            operationLogsDTO.setContent(content);
            operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
            operationLogsDTO.setCreator("系统");
            cgnciOperationLogsService.saveLog(operationLogsDTO);
        }*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void back(FlowTaskBackDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验年度承保计划是否存在
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = this.getById(flowTaskDTO.getFormId());
        if (VerifyUtils.isEmpty(reInsuranceCompanyDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        FlowTaskVO back = approvalService.back(flowTaskDTO);

        // 回调审批通过状态流程
        reInsuranceCompanyDO.setStatus(back.getStatus());
        // 退回设置状态为 失效
        reInsuranceCompanyDO.setIsEffective("0");
        this.updateById(reInsuranceCompanyDO);

        // 查询再保公司账户信息
        List<CgnciReInsuranceCompanyAccountDO> list = reInsuranceCompanyAccountService.list(new LambdaQueryWrapper<CgnciReInsuranceCompanyAccountDO>()
                .eq(CgnciReInsuranceCompanyAccountDO::getCompanyId, reInsuranceCompanyDO.getId()));
        // 退回设置状态为 失效
        list.forEach(account -> {
            account.setIsEffective("0");
        });
        //记录操作日志
        ApprovalRecordVO approvalRecord = approvalRecordService.getPreviousApprovalRecord(reInsuranceCompanyDO.getId());
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(reInsuranceCompanyDO.getId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.REINSURANCECOMPANY.getCode());
        if(approvalRecord.getGroupID().equals(ApprovalConfigEnum.APPROVAL_CONFIG_004.getGroupId())){
            operationLogsDTO.setOperationType(OperationTypeEnum.EDIT_REINSURANCE_COMPANY_AUDIT_BACK.getCode());
        }else {
            operationLogsDTO.setOperationType(OperationTypeEnum.REINSURANCE_COMPANY_AUDIT_BACK.getCode());
        }
        operationLogsDTO.setCreator(user.getNameAndCode());
        operationLogsDTO.setContent(flowTaskDTO.getApproverOpinions());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
        /*String content = String.format("{%s}{%s}{%s} 流转至{%s}", back.getStatus(), approvalRecord.getTaskType(), approvalRecord.getTaskId(), approvalRecord.getCurrentApproverAndName());
        operationLogsDTO.setContent(content);
        operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
        operationLogsDTO.setCreator("系统");
        cgnciOperationLogsService.saveLog(operationLogsDTO);*/
        reInsuranceCompanyAccountService.updateBatchById(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOut(Long id) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        CgnciReInsuranceCompanyDO reInsuranceCompanyDO = this.baseMapper.selectById(id);
        if (VerifyUtils.isEmpty(reInsuranceCompanyDO)) {
            throw new GlobalException(ResponseCodeEnum.PARAMS_ILLEGAL, "inPlanId有误");
        }
        // 判断当前状态是否为 录入中
        if (!"0".equals(reInsuranceCompanyDO.getStatus()) && !"2".equals(reInsuranceCompanyDO.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "当前状态不能注销");
        }
        approvalService.cancelTask(FlowTaskCancelDTO.builder().formId(String.valueOf(reInsuranceCompanyDO.getId())).formNo(reInsuranceCompanyDO.getFormNo()).build());
        // 回调提交审核状态流程
        reInsuranceCompanyDO.setStatus("4");
        reInsuranceCompanyDO.setIsAffiliated("0");
        this.updateById(reInsuranceCompanyDO);
        //注销操作日志
        ApprovalRecordVO approvalRecordVO = approvalRecordService.getPreviousApprovalRecord(id);
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(reInsuranceCompanyDO.getId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.REINSURANCECOMPANY.getCode());
        if(approvalRecordVO.getGroupID().equals(ApprovalConfigEnum.APPROVAL_CONFIG_004.getGroupId())){
            operationLogsDTO.setOperationType(OperationTypeEnum.CANCEL_EDIT_REINSURANCE_COMPANY.getCode());
        }else {
        operationLogsDTO.setOperationType(OperationTypeEnum.CANCEL_REINSURANCE_COMPANY.getCode());
        }
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
    }

    @Override
    public List<ApprovalRecordVO> log(Long id) {
        List<CgnciApprovalRecordDO> approvalRecordDOList = approvalRecordMapper.selectList(new LambdaQueryWrapper<CgnciApprovalRecordDO>().eq(CgnciApprovalRecordDO::getFormId, id));
        return ConvertUtils.convert(approvalRecordDOList, ApprovalRecordVO.class);
    }
}
